package org.soul.mgwt.client.widget;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.Timer;
import com.googlecode.mgwt.ui.client.widget.CellList;
import com.googlecode.mgwt.ui.client.widget.celllist.Cell;

public class CsCellList<T> extends CellList<T>{

	private List<T> list = new ArrayList<T>();
	interface Template extends SafeHtmlTemplates {
		@SafeHtmlTemplates.Template("<li __idx=\"{0}\" class=\"{1}\">{2}</li>")
		SafeHtml li(int idx, String classes, SafeHtml cellContents);

	}

	private static final Template LI_TEMPLATE = GWT.create(Template.class);

	public CsCellList(Cell<T> cell) {
		super(cell);
	}
	
	@Override
	/**
	 * Render a List of models in this cell list
	 * 
	 * @param models the list of models to render
	 */
	public void render(List<T> models) {

		list = models;
		SafeHtmlBuilder sb = new SafeHtmlBuilder();

		for (int i = 0; i < models.size(); i++) {

			T model = models.get(i);

			SafeHtmlBuilder cellBuilder = new SafeHtmlBuilder();

			String clazz = "";
			if (cell.canBeSelected(model)) {
				clazz = css.group() + " ";
			}
			if (i == 0) {
				clazz += css.first() + " ";
			}

			if (models.size() - 1 == i) {
				clazz += css.last() + " ";
			}

			cell.render(cellBuilder, model);

			sb.append(LI_TEMPLATE.li(i, clazz, cellBuilder.toSafeHtml()));
		}

		final String html = sb.toSafeHtml().asString();

		getElement().setInnerHTML(html);

		if (models.size() > 0) {
			String innerHTML = getElement().getInnerHTML();
			if ("".equals(innerHTML.trim())) {
				fixBug(html);
			}
		}

	}
	protected void fixBug(final String html) {
		new Timer() {

			@Override
			public void run() {
				getElement().setInnerHTML(html);
				String innerHTML = getElement().getInnerHTML();
				if ("".equals(innerHTML.trim())) {
					fixBug(html);

				}

			}
		}.schedule(100);
	}

	public final List<T> getList(){
		return list;
	}
	
	public final T getItem ( int index ){
/*		if ( list.size() < index ) throw new IndexOutOfBoundsException("The list is shorter then index!");
		else
*/			return list.get(index);
		
			
	}
}
